package cloud.maque.sso.client.filter;

import cloud.maque.common.captcha.conf.CaptchaProperties;
import cloud.maque.common.core.response.R;
import cn.dev33.satoken.SaManager;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Cleanup;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component
public class CaptchaVerificationFilter extends OncePerRequestFilter implements InitializingBean {

    @Autowired
    CaptchaProperties captchaProperties;

    List<String> urlmap = new ArrayList<>();

    /**
     * ant表达式工具
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 初始化，将配置文件中url添加到集合中
     */
    @Override
    public void afterPropertiesSet() {

        urlmap.add("/passwordLogin");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        if (!captchaProperties.getEnable()) {
            filterChain.doFilter(request, response);
            return;
        }

        if (!getMatchUrl(request)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 从请求头中获取验证码
        String captcha = request.getParameter("code");
        String codeId = request.getParameter("codeId");

        try {
            // 检查验证码是否为空
            if (captcha == null || captcha.isEmpty()) {
                Print(response, "验证码不能为空");
                return;
            }

            if (StrUtil.isEmptyIfStr(codeId)) {
                Print(response, "缺少验证参数");
                return;
            }
            // 这里应该有一个方法来验证验证码是否正确
            boolean isCaptchaValid = checkCaptcha(captcha, codeId);

            // 2、校验通过，删除验证码
            SaManager.getSaTokenDao().delete("captcha:" + codeId);

            if (!isCaptchaValid) {
                Print(response, "验证码错误");
                return;
            }

            // 如果验证码正确，继续执行后续操作
            filterChain.doFilter(request, response);
        } catch (Exception ex) {
            Print(response, ex.getMessage());
        }
    }

    private boolean checkCaptcha(String code, String codeId) {
        String realCode = SaManager.getSaTokenDao().get("captcha:" + codeId);
        // 1、校验验证码是否正确
        return code.equalsIgnoreCase(realCode);
    }

    private void Print(HttpServletResponse response, String msg) throws IOException {
        R r = R.error(msg);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        PrintWriter printWriter = response.getWriter();
        printWriter.write(JSON.toJSONString(r));
    }

    private Boolean getMatchUrl(HttpServletRequest request) {
        for (String url : urlmap) {
            if (pathMatcher.match(request.getContextPath() + url, request.getRequestURI())) {
                return true;
            }
        }
        return false;
    }
}